#!/usr/bin/python
# -*- coding:utf-8 -*-

import os
import time
import sys
import subprocess
class Shell(object) :
 def runCmd(self, cmd) :
  res = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
  sout ,serr = res.communicate()   
  print "返回码：", res.returncode
  print "标准输出：", sout
  print "标准错误：", serr
  return res.returncode, sout, serr, res.pid
def run_shell(cmd):
    os.system('echo "运行命令 --- {0}"'.format(cmd))
shell = Shell()
try:
    rootdir = sys.argv[1]
    os.chdir(rootdir)
    result = shell.runCmd('pwd')
    rootdir=result[1].replace('\n','')
    print "rootdir ="+rootdir
except:
    print 'sys.argv[1] must set project dir'
    exit(1)
try:
    project = sys.argv[2]
    print "project ="+project
except:
    print 'sys.argv[2] must set the projectpre'
    exit(1)

url = "192.168.1.222"
port= "31901"

for filename in os.listdir(rootdir):
    pathname = os.path.join(rootdir, filename)
    if (os.path.isdir(pathname)):
        os.chdir(pathname)
        print "进入到目录"+pathname
        time.sleep(1)
        run_shell("ssh -p {0} admin@{1} gerrit create-project {2}-{3}".format(port,url,project,filename))
        run_shell("git init")
        run_shell("git add .")
        run_shell('git commit -m "first commit"')
        run_shell("git push ssh://admin@{0}:{1}/{2}-{3} *:*".format(url,port,project,filename))
        os.chdir(rootdir)
        print '回到根目录:'+rootdir
        time.sleep(1)

print '回到根目录:'+rootdir
os.chdir(rootdir)
run_shell("ssh -p {0} admin@{1} gerrit create-project {2}-build-makefile".format(port,url,project))
run_shell("git init")
for filename in os.listdir(rootdir):
    if (os.path.isfile(filename)):
        run_shell("git add {0}".format(filename))
run_shell("git commit -m 'first commit'")
run_shell("git push ssh://admin@{0}:{1}/{2}-build-makefile *:*".format(url,port,project))
